package afcp.alumni.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import afcp.alumni.csv.IncorrectCSVHeaderException;
import afcp.alumni.csv.MemberReader;
import afcp.alumni.model.CsvFileProperties;
import afcp.alumni.model.db.Member;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreInputStream;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

public class UploadServiceBlobstore implements UploadService {

	private static final Log logger = LogFactory.getLog(UploadServiceBlobstore.class);
	
	public String url = "/upload";
	
	UploadServiceBlobstore(String url) {
		this.url = url;
	}

	private static MemberService memberService = SF.member();

	private static BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();
	
	public String getUploadUrl() {
		return blobstoreService.createUploadUrl(url);
	}
	
	public List<Member> readUpload(HttpServletRequest request, CsvFileProperties file) {
		
		List<Member> failed = new LinkedList<>();

		Map<String, List<BlobKey>> blobs = blobstoreService
				.getUploads(request);
//		List<BlobKey> blobKeys = blobs.get(AdminAction.FORM_FILE_PARAM);
		for (List<BlobKey> blobKeys : blobs.values()) {
			for (BlobKey blobKey : blobKeys) {

				MemberReader memberReader = null;
				try {
					
					InputStream inputStream = new BlobstoreInputStream(blobKey);
					
					memberReader = new MemberReader(inputStream, file);
					
					for (Member member : memberReader) {
						boolean success = memberService.addMember(member);
						if (!success) {
							logger.warn("The member "
									+ member.getFirstName() + " "
									+ member.getLastName() + " (id: "
									+ member.getId()
									+ ") already exists in datastore.");
							failed.add(member);
						}
					}

//				} catch (FileNotFoundException e) {
//					logger.error(
//							"The uploaded file corresponding to the BlobKey "
//									+ blobKey
//									+ " has not been found. Please check how the Google Blobstore API is used.",
//							e);
				} catch (IOException e) {
					logger.error(
							"A problem occurred while getting the uploaded file corresponding to the BlobKey "
									+ blobKey + ".", e);
				} catch (IncorrectCSVHeaderException e) {
					logger.error(
							"The uploaded CSV file has an incorrect header. It seems not to match the expected Member format. Expected: 4 columns.",
							e);
				} finally {
					try {
						if (memberReader != null)
							memberReader.close();
					} catch (IOException e) {
						logger.warn("Can't close CsvReader", e);
					}
					blobstoreService.delete(blobKey);
				}
			}
		}
		return failed;
	}

}
